package io.choerodon.gateway.filter;

import org.hzero.core.base.BaseHeaders;
import org.hzero.core.util.ServerRequestUtils;
import org.hzero.gateway.helper.entity.CheckState;
import org.hzero.gateway.helper.entity.PermissionDO;
import org.hzero.gateway.helper.entity.RequestContext;
import org.hzero.gateway.helper.exception.FilterMismatchException;
import org.hzero.gateway.helper.filter.GetPermissionFilter;
import org.hzero.gateway.helper.service.PermissionService;
import org.hzero.starter.keyencrypt.core.EncryptContext;
import org.hzero.starter.keyencrypt.core.EncryptType;
import org.hzero.starter.keyencrypt.core.IEncryptionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @author scp
 * @since 2022/10/18
 * {@link #getMenuId(RequestContext)} ()} 覆盖该方法
 */
@Service
@Primary
public class GetPermissionC7nFilter extends GetPermissionFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(GetPermissionC7nFilter.class);

    @Autowired
    @Qualifier("helperPermissionService")
    private PermissionService permissionService;
    @Autowired
    private IEncryptionService encryptionService;

    @Override
    protected Long getMenuId(RequestContext context) {
        Object servletRequest = context.getServletRequest();
        String menuId = ServerRequestUtils.getHeaderValue(servletRequest, BaseHeaders.H_MENU_ID);

        if (ObjectUtils.isEmpty(menuId)) {
            return null;
        }

        Long id = null;
        try {
            if (encryptionService.isCipher(menuId)) {
                EncryptContext.setEncryptType(EncryptType.ENCRYPT.name());
                menuId = encryptionService.decrypt(menuId, "", context.request.accessToken);
                EncryptContext.clear();
            }
            id = Long.parseLong(menuId);
        } catch (NumberFormatException e) {
            LOGGER.warn("Header of [{}] format, header value is [{}]", BaseHeaders.H_MENU_ID, menuId);
        }
        return id;
    }

}
